package lib.modules;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import com.google.gdata.data.calendar.CalendarEntry;

import lib.base.EgoAuth;
import lib.base.EgoHolidayManager;
import lib.base.EgoModule;
import lib.data.Department;
import lib.data.Employee;

/**
 * This module can move all calendars from a system account
 * to another without lost of data
 * 
 * @author jonas
 */
public class ModAccountMove extends EgoModule {

	/**
	 * @param req
	 */
	public ModAccountMove(HttpServletRequest req) throws Exception
	{
		super(req);
		if (!((EgoAuth) req.getSession().getAttribute("auth")).isAdmin())
		{
			req.setAttribute("no_admin", true);
		}
		req.getSession().setAttribute("template", "modules/account_move/index.jsp");
	}

	/* (non-Javadoc)
	 * @see lib.base.EgoModule#work()
	 */
	@Override
	public void work() throws Exception
	{
		if (_request.getParameter("action") != null)
		{
			if (
				_request.getParameter("action").toString().equals( "move" )
				&& _request.getAttribute("no_admin") == null
			) {
				/*
				 * move account
				 */
				
				// check if the movement will work
				CalendarEntry test_cal = _curCust.holidayManager.createTestCalendar(_curCust);
				_curCust.holidayManager.moveCalendar(test_cal, _request.getParameter("systemAccount"));
				EgoHolidayManager _checkHM = new EgoHolidayManager(_request.getParameter("systemAccount"), _request.getParameter("pwd"));
				if (_checkHM.getTestCalendar(_curCust) == null)
				{
					// null => failed
					_request.setAttribute("ajax_return", "test_cal_failed");
				} else
				{
					// all right, continue
				
					// move all employee calendars
					ArrayList<Employee> emps = _curCust.getAllEmployees();
					for (int i=0; i<emps.size(); i++)
					{
						_curCust.holidayManager.moveCalendar(
							_curCust.holidayManager.getCalendar(emps.get(i))
							, _request.getParameter("systemAccount")
						);
					}
					
					// move all department calendar
					ArrayList<Department> deps = _curCust.getAllDepartments();
					for (int i=0; i<deps.size(); i++)
					{
						_curCust.holidayManager.moveCalendar(
							_curCust.holidayManager.getCalendar(deps.get(i))
							, _request.getParameter("systemAccount")
						);
					}
					
					// update systemAccount DB-field
					_curCust.setField("systemAccount", _request.getParameter("systemAccount"));
					_curCust.setField("password", _request.getParameter("pwd"));
					_curCust.setField("temporarySystemAccount", "");
					_curCust.update();
					
					// refresh customer
					_curCust.refresh();
				}
				// testCal delete
				try {
					test_cal.delete();
				} catch (Exception e)
				{
					// ignore errors
				}
				
				_request.getSession().setAttribute("template", "ajax_return.jsp");
			}
		}
	}
}
